# 问答相关的
from flask import Blueprint, request, render_template, g, redirect, url_for
from .forms import QuestionForm,AnswerForm
from models import QuestionModel,AnswerModel
from exts import db
from decorators import login_required
# 首页


bp = Blueprint("qa", __name__,url_prefix="/")
@bp.route( "/" )
def index():
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()   # order_by的作用就是排序
    return render_template("index.html", questions=questions)



# GET:从服务器上获取数据   POST:将客户端的数据提交给服务器
@bp.route("/qa/public", methods = ['GET','POST'])
@login_required  # 会把函数public_question传入
def public_question():
    # 如果未登录就发布问答的话，可能造成网站崩溃，所以就让他跳转到登录界面
    if request.method == 'GET':
        return render_template("public_question.html")
    else:
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title, content=content, author=g.user)  # 将获取的数据提交到数据库中
            db.session.add(question)
            db.session.commit()
            # todo：跳转到这篇问答的详情页
            return redirect("/")
        else:
            print(form.errors)
            return redirect(url_for("qa.public_question"))

@bp.route("/qa/detail/<qa_id>")
def qa_detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template("detail.html", question=question)


@bp.route("/answer/public", methods=['POST'])  # 还有一种写法:@bp.post("/answer/public")
@login_required   # 验证用户有没有登录
def public_answer():
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        question_id = form.question_id.data
        answer = AnswerModel(content=content, question_id=question_id, author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.qa_detail", qa_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for("qa.qa_detail", qa_id=request.form.get("question_id")))

# 搜索框的视图函数
@bp.route("/search")
def search():  # 不需要登录就可以使用
    q = request.args.get("q")
    # 然后在数据库中问题的这个表中搜索
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template("index.html", questions=questions)

























































